//
//  AFSoundItem.m
//  AFSoundManager-Demo
//
//  Created by Alvaro Franco on 20/01/15.
//  Copyright (c) 2015 AlvaroFranco. All rights reserved.
//

#import "AFSoundItem.h"
#import "AFSoundManager.h"

@interface AFSoundItem ()

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *album;
@property (nonatomic, strong) NSString *artist;
@property (nonatomic, strong) UIImage *artwork;

@property (nonatomic, strong) NSURL *URL;

@end

@implementation AFSoundItem

- (instancetype)initWithLocalResource:(NSString *)name atPath:(NSString *)path {
    self = [super init];

    if (self) {
        _type = AFSoundItemTypeLocal;

        NSString *itemPath;

        if (!path) {
            NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
            itemPath = [resourcePath stringByAppendingPathComponent:name];
        } else {
            itemPath = [path stringByAppendingPathComponent:name];
        }

        _URL = [NSURL fileURLWithPath:itemPath];

        [self fetchMetadata];
    }

    return self;
}

- (instancetype)initWithLocalURL:(NSURL *)URL {
    self = [super init];

    if (self) {
        _type = AFSoundItemTypeLocal;

        _URL = URL;

        [self fetchMetadata];
    }

    return self;
}

- (instancetype)initWithStreamingURL:(NSURL *)URL {
    self = [super init];

    if (self) {
        _type = AFSoundItemTypeStreaming;

        _URL = URL;

        [self fetchMetadata];
    }

    return self;
}

- (void)fetchMetadata {
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:_URL];

    NSArray *metadata = [playerItem.asset commonMetadata];

    for (AVMetadataItem *metadataItem in metadata) {
        __weak typeof(self) OC = self;

        [metadataItem loadValuesAsynchronouslyForKeys:@[AVMetadataKeySpaceCommon] completionHandler:^{
            if ([metadataItem.commonKey isEqualToString:@"title"]) {
                OC.title = (NSString *)metadataItem.value;
            } else if ([metadataItem.commonKey isEqualToString:@"albumName"]) {
                OC.album = (NSString *)metadataItem.value;
            } else if ([metadataItem.commonKey isEqualToString:@"artist"]) {
                OC.artist = (NSString *)metadataItem.value;
            } else if ([metadataItem.commonKey isEqualToString:@"artwork"]) {
                if ([metadataItem.keySpace isEqualToString:AVMetadataKeySpaceID3]) {
                    OC.artwork = [UIImage imageWithData:[[metadataItem.value copyWithZone:nil] objectForKey:@"data"]];
                } else if ([metadataItem.keySpace isEqualToString:AVMetadataKeySpaceiTunes]) {
                    OC.artwork = [UIImage imageWithData:[metadataItem.value copyWithZone:nil]];
                }
            }
        }];
    }
}

- (void)setInfoFromItem:(AVPlayerItem *)item {
    _duration = CMTimeGetSeconds(item.duration);
    _timePlayed = CMTimeGetSeconds(item.currentTime);
}

@end
